﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Generic.Sync ;
namespace WayneGameSolution.Chat
{
    public abstract class ChatChannelBase : IChatChannel
    {
        public ChatChannelBase()
        {
            this.LastReceivedTime = new Dictionary<string, DateTime>();

            this.MessageLinkList = new RecycleList <IChatMessage>();
            ID = Guid.NewGuid().ToString();
            Name = "Chat";
            TimeoutSecond = 30;
            Type = ChannelType.GuildChannel;


        }

        public ChatChannelBase(string id, string name, int timeoutSecond, ChannelType type)
        {
            this.LastReceivedTime = new Dictionary<string, DateTime>();
            this.MessageLinkList = new RecycleList<IChatMessage>();
            ID = id;
            Name = name;
            TimeoutSecond = timeoutSecond;
            Type = type;


        }
     

        protected RecycleList<IChatMessage> MessageLinkList
        {
            get;
            set;
        }

        #region IChatChannel Members

        public void Clear()
        {

            MessageLinkList = new RecycleList<IChatMessage>();
        }








        abstract public IEnumerable<IChatMessage> GetUserMessage(string user);


        public void ReceiveMessage(IChatMessage message)
        {
            MessageLinkList.StackOn(message);
            ClearTimeouted();
        }

        public string ID
        {
            get;
            protected set;
        }

        public string Name
        {
            get;
            protected set;
        }

        public int TimeoutSecond
        {
            get;
            set;  
        }

        public ChannelType Type
        {
            get;
            protected set;
        }

        public void ClearTimeouted()
        {
            var nt = DateTime.Now;
            MessageLinkList.RecycleFromButtom(n => n.TimeStamp.AddSeconds(TimeoutSecond) < nt);
        }


        public IDictionary<string, DateTime> LastReceivedTime
        {
            get;
            protected set;
        }




        #endregion


        protected IEnumerable<IChatMessage> SearchMessagesFromLast(DateTime OutTime)
        {
            foreach (var tmpn in MessageLinkList)
            {
                if (tmpn.Value.TimeStamp <= OutTime)
                    yield break;
                else
                    yield return tmpn.Value;
            
            }         
            

        }


    }
}
